package pl.edu.agh.mguesser.game;

import pl.edu.agh.mguesser.game.answer.Answer;
import org.springframework.stereotype.Service;
import pl.edu.agh.mguesser.game.stats.ScoreContainer;
import pl.edu.agh.mguesser.player.PlayerException;
import pl.edu.agh.mguesser.user.User;

/**
 * @author keiran
 */
@Service
public class OneByOneGameFlow extends AbstractGameFlow {

    @Override
    public void play() throws GameFlowException {
        GameSettings settings = getGameSettings();
        
        if(settings == null) {
            throw new IllegalStateException();
        }
        
        try {
            ScoreContainer scoreContainer = createScoreContainer();
            
            for(int i = 0; i < settings.getRounds(); i++) {
                newRoundEvent(i + 1, settings.getRounds());
                
                for(User user : settings.getUsers()) {
                    userChangedEvent(user.getName());
                    
                    singleTurn(user.getName(), scoreContainer);
                }
            }
            
        } catch(PlayerException ex) {
            throw new GameFlowException(ex);
            
        }
    }

    void singleTurn(String userName, ScoreContainer scoreContainer) throws PlayerException {
        getPlayer().play();
        int waited = waitForStop();
        getPlayer().stop();
        
        Answer answer = getAnswer();
        scoreContainer.addScore(userName, answer.getScore(waited));
        
        getPlayer().next();
    }
    
    @Override
    public void donePlaying() {
        try {
            gameDoneEvent();
            
        } finally {
            super.donePlaying();
            
        }
    }

}
